package com.shop.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class ConnectionUtils {
	private static String driverClass;
	private static String url;
	private static String user;
	private static String password;
	private static Properties pro = new Properties();
	private static Connection conn;
	
	static{
		try {
			//1.��Դ�ļ�����
			InputStream in = ConnectionUtils.class.getResourceAsStream("db.properties");
			//InputStream in = new FileInputStream("/shopping/db.properties");
			pro.load(in);
			//2.��ȡ�����ļ���Ϣ
			driverClass = pro.getProperty("driverClass");
			url = pro.getProperty("url");
			user = pro.getProperty("user");
			password = pro.getProperty("password");
			
			//3.��������
			Class.forName(driverClass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws SQLException{
		return DriverManager.getConnection(url, user, password);
	}

	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		if(rs !=null){try{rs.close();}catch(SQLException e){e.printStackTrace();}};
		if(stmt !=null){try{stmt.close();}catch(SQLException e){e.printStackTrace();}};
		if(conn !=null){try{conn.close();}catch(SQLException e){e.printStackTrace();}};
	}

	public static void close(Statement stmt, Connection conn) {
		close(null,stmt,conn);
	}
	
	
	public static void close(ResultSet rs, PreparedStatement pstmt, Connection conn) {
		if(rs !=null){try{rs.close();}catch(SQLException e){e.printStackTrace();}};
		if(pstmt !=null){try{pstmt.close();}catch(SQLException e){e.printStackTrace();}};
		if(conn !=null){try{conn.close();}catch(SQLException e){e.printStackTrace();}};
	}

	public static void close(PreparedStatement pstmt, Connection conn) {
		close(null,pstmt,conn);
	}

}
